package com.dxx.cloud.admin.config;

import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import com.dxx.cloud.admin.module.entity.UserEntity;
import org.dromara.common.satoken.utils.LoginHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 小程序当前登录用户信息
 *
 * @author liukaixiong
 * @date 2024/5/30 - 13:02
 */
public class UserMiniAppHelper {
    public static final String XCX_USER_INFO = "xcx_user_info";
    public static final String XCX_STUDENT_ID = "xcx_student_id";
    public static final String XCX_MOBILE = "xcx_mobile";
    public static final String XCX_OPEN_ID = "xcx_open_id";
    public static final String XCX_FAMILY_ID = "xcx_family_id";
    public static final String XCX = "xcx";
    private final static Logger LOG = LoggerFactory.getLogger(UserMiniAppHelper.class);
    /**
     * 默认小程序操作类
     */
    private final static StpLogic stpLogic = new StpLogicJwtForSimple("xcx");

    public static void checkLogin() {
        stpLogic.checkLogin();
    }

    /**
     * 生成token
     *
     * @param student
     */
    public static void generateToken(UserEntity student) {
        LoginHelper.getUserId();

    }

    public static void logoutById(Long studentId) {
        stpLogic.logout(studentId);
    }

    public static void logout() {
        stpLogic.logout();
    }

    public static String getToken() {
        return stpLogic.getTokenValue();
    }

    /**
     * 获取当前登录人用户编号
     *
     * @return
     */
    public static Long getUserId() {
        return getObject(XCX_STUDENT_ID, Long.class);
    }

    public static Long getUserIdIfLogin() {
        Long userId = null;
        if (stpLogic.isLogin()) {
            userId = getUserId();
        }
        return userId;
    }

    /**
     * 获取当前登录人手机号
     *
     * @return
     */
    public static String getPhone() {
        return getObject(XCX_MOBILE, String.class);
    }

    public static String getPhoneIfLogin() {
        String phone = null;
        if (stpLogic.isLogin()) {
            phone = getPhone();
        }
        return phone;
    }

    private static <T> T getObject(String key, Class<T> clazz) {
        final Object value = stpLogic.getTokenSession().get(key);
        return (T) value;
    }

}
